<template>
  <div>
 <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片 -->
<el-card>
  <el-row>
    <!-- 添加角色信息 -->
    <el-col :span="4">
       <el-button type=primary  @click="addrolesdialogVisible = true">添加角色</el-button>
     </el-col>
  </el-row>
  <!-- 角色列表 -->
  <el-table
      stripe
      border
      :data="rolesList"
      style="width: 100%">
      <!-- 展开权限列 expand -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <!-- {{scope.row}} -->
          <div>
            <!--一级权限 -->
            <el-row class="v-center" v-for="item1 in scope.row.children" :key="item1.id">
              <!-- 必须指定span，否则他们都会列在第一列 -->
              <el-col :span="5" ><el-tag>{{item1.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
              <!-- 二级权限 -->
              <el-col :span="19" >
                <el-row class="v-center" v-for="item2 in item1.children" :key="item2.id">
                  <el-col :span="6" ><el-tag type="success">{{item2.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                   <!-- 三级权限 -->
                   <el-col class="v-center" :span="18" >
                     <el-tag closable @close="removeRight(scope.row,item3.id)" v-for="item3 in item2.children" :key="item3.id" type="warning">{{item3.authName}}</el-tag>
                   </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- pre 树结构 -->
            <!-- <pre>{{scope.row}}</pre> -->
          </div>
        </template>
      </el-table-column>
      <!-- 索引 index -->
      <el-table-column
        type="index"
        label="序号">
        </el-table-column>
        <el-table-column
        prop="roleName"
        label="角色名称">
        </el-table-column>
        <el-table-column
        prop="roleDesc"
        label="角色描述">
        </el-table-column>
        <el-table-column
        label="操作">
        <template slot-scope="scope">
          <div>
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditroledialog(scope.row.id)">编辑</el-button>
            <el-button type="warning" icon="el-icon-delet" size="mini" @click="deletebyroleid(scope.row.id)">删除</el-button>
            <el-tooltip effect="dark" content="分配角色权限" placement="top" :enterable="false">
<el-button type="danger" icon="el-icon-setting" size="mini" @click="showSetingsdialog(scope.row)">分配权限</el-button>    </el-tooltip>
          </div>
        </template>
        </el-table-column>
      </el-table>
</el-card>
<!-- 添加角色 -->
<el-dialog
  title="添加角色"
  :visible.sync="addrolesdialogVisible"
  width="50%"
  @close="resetaddRoleForm">
  <el-form :model="addRoleForm"  ref="addRoleFormRef" label-width="100px">
  <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="addRoleForm.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="addRoleForm.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addrolesdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addrole">确 定</el-button>
  </span>
</el-dialog>
<!-- 修改角色-->
<el-dialog
  title="修改角色信息"
  :visible.sync="editRoledialogVisible"
  width="50%"
  @close="reseteditRoleForm">
  <el-form :model="editRoleForm" ref="editRoleFormRef" label-width="100px">
  <el-form-item label="角色ID" >
    <el-input v-model="editRoleForm.roleID" disabled></el-input>
  </el-form-item>
  <el-form-item label="角色名称" >
    <el-input v-model="editRoleForm.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述">
    <el-input v-model="editRoleForm.roleDesc"></el-input>
  </el-form-item>
  </el-form>
   <span slot="footer" class="dialog-footer">
    <el-button @click="editRoledialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editrole">确 定</el-button>
  </span>
</el-dialog>
<!-- 分配权限 -->
<el-dialog
  title="分配权限"
  :visible.sync="setRightdialogVisible"
  width="50%"
  @close="resetrhighttree">
  <el-tree show-checkbox :data="rightlist" :props="treeProps" ref="treeref" node-key="id" default-expand-all :default-checked-keys="defkeys"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRights">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      addrolesdialogVisible: false,
      editRoledialogVisible: false,
      setRightdialogVisible: false,
      rolesList: [],
      addRoleForm: {},
      editRoleForm: {},
      rightlist: [],
      // 树型组件的绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形组件绑定的默认已经选中的节点ID值数组
      defkeys: [],
      // 当前即将分配权限的角色id
      roleid: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.erro(res.meta.msg)
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    // 添加角色
    addrole () {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        // console.log(res)
        if (res.meta.status !== 201) return
        this.addrolesdialogVisible = false
        // 重新获取用户列表
        this.getRolesList()
      })
    },
    // 重置表单
    resetaddRoleForm () {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 重置修改表单
    reseteditRoleForm () {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 编辑角色
    async showeditroledialog (id) {
      this.editRoledialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      // console.log(res)
      this.editRoleForm = res.data
    },
    editrole () {
      this.editRoledialogVisible = false
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editRoleForm.roleId, { roleName: this.editRoleForm.roleName, roleDesc: this.editRoleForm.roleDesc })
        // console.log(res)
        if (res.meta.status !== 200) return
        // 重新获取用户列表
        this.getRolesList()
      })
    },
    // 删除角色
    async deletebyroleid (id) {
      const deleteresult = await
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '取消删除'
        // })
      })
      if (deleteresult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '取消删除'
        })
      }
      // await 不允许嵌套在then函数里面，所以写在外面
      const { data: res } = await this.$http.delete('roles/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'info',
          message: '删除失败'
        })
      }
      // 重新获取角色列表
      this.getRolesList()
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
    },
    // 删除用户权限
    async removeRight (role, rightid) {
      const deleteresult = await
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '取消删除'
        // })
      })
      if (deleteresult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '取消删除'
        })
      }
      // await 不允许嵌套在then函数里面，所以写在外面
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'info',
          message: '删除失败'
        })
      }
      // 这里表格会自动合起来，为了更加友好的用户体验，直接渲染刚刚获取的权限，不再渲染角色
      // this.getRolesList()
      role.children = res.data
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
    },
    // 分配角色权限
    async showSetingsdialog (role) {
      this.roleid = role.id
      this.setRightdialogVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      this.rightlist = res.data
      // 生成默认选中数组
      this.addnodes(role, this.defkeys)
    },
    async setRights () {
      // 生成选中得权限数组
      const keys = [...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys()]
      // 数组要以逗号分隔开
      const idstr = keys.join(',')
      // console.log(keys)
      const { data: res } = await this.$http.post(`roles/${this.roleid}/rights`, { rids: idstr })
      console.log(res)
      this.setRightdialogVisible = false
      this.getRolesList()
    },
    // 递归函数动态添加三级节点的id值到 defkeys: []
    addnodes (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.addnodes(item, arr)
      })
    },
    // 重置树对话框
    resetrhighttree () {
      this.defkeys = []
    }
  }
}

</script>
<style scoped>
.el-tag{
  margin: 7px;
}
.el-col{
  border-bottom: 1px solid #eee;
}
.v-center{
  display: flex;
  align-items: center;
}
</style>
